package com.xique.park.command.handler;

import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.utils.file.FileUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.park.api.IParkIpcCommandApi;
import com.xique.park.command.handler.base.BaseCommand;
import com.xique.park.constant.ParkApiName;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 下载文件
 *
 * @author WLD
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class DownFileCommandHandler extends BaseCommand {

    private final IParkIpcCommandApi parkIpcCommandApi;

    @Override
    public String getServiceName() {
        return ParkApiName.COMMAND_FILE_DOWNLOAD;
    }

    @Override
    public String getVersion() {
        return ParkApiName.VER_1_0;
    }

    @Override
    public AjaxResult issue(Long parkId, Long laneId, String mngTypeIds, String sn,
                            MultipartFile file, String fileName, String cmd) {
        checkParkId(parkId);
        checkSn(sn);

        try {
            Map<String, Object> params = new HashMap<>(2);

            // http请求设备固件升级api接口
            FileSystemResource resource = new FileSystemResource(FileUtils.multipartFileToFile(file));
            JSONObject baseObj = getBaseObj(sn, getServiceName(), getVersion());
            params.put("data", baseObj);
            params.put("file", resource);

            AjaxResult issueResult = parkIpcCommandApi.issue(params);
            log.info("[停车系统]下载文件命令下发，服务名：{}，版本号：{}，车场ID：{}，设备编号：{}，下发参数：{}，下发结果：{}",
                    getServiceName(), getVersion(), parkId, sn, params, issueResult);

            updateCommonInfo(cmd,params,issueResult);

            return issueResult;

        } catch (Exception e) {
            e.printStackTrace();
            log.error("[停车系统]下载文件命令下发，系统异常，异常信息为：{}", e.getMessage());
            return AjaxResult.error("文件下载命令下发失败：" + e.getMessage());
        }
    }

}
